package com.shop.cereshop.app.controller.kf;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shop.cereshop.app.param.common.CommonIdParam;
import com.shop.cereshop.app.redis.service.api.StringRedisService;
import com.shop.cereshop.app.service.customer_service.CereCustomerServiceConfigService;
import com.shop.cereshop.commons.constant.WxCpConstants;
import com.shop.cereshop.commons.domain.customer_service.CereCustomerServiceConfig;
import com.shop.cereshop.commons.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 客服模块
 */
@RestController
@RequestMapping("kf")
/**
 * 注解方式生成日志对象，指定topic生成对象类名
 */
@Slf4j(topic = "KfController")
@Api(value = "客服模块", tags = "客服模块")
public class KfController {

    @Autowired
    private WxCpServiceImpl wxCpServiceImpl;

    @Autowired
    private WxCpTpService wxCpTpService;

    @Autowired
    private StringRedisService stringRedisService;

    @Autowired
    private CereCustomerServiceConfigService cereCustomerServiceConfigService;

    @GetMapping("getH5Kf")
    @ApiOperation(value = "查询H5客服", notes = "id参数传店铺id, 不传则返回平台端的客服")
    public Result<Map<String, String>> getH5Kf(CommonIdParam param) {
        Map<String, String> map = new HashMap<>();
        map.put("url", "");
        try {
            if (param == null || param.getId() == null || param.getId() == 0) {
                String kfListResult = wxCpServiceImpl.get(WxCpConstants.API_KF_LIST, null);
                JSONObject obj = JSON.parseObject(kfListResult);
                if (obj != null) {
                    JSONArray array = obj.getJSONArray("account_list");
                    if (array != null && array.size() > 0) {
                        Collections.shuffle(array);
                        JSONObject kfParamObj = new JSONObject();
                        kfParamObj.put("open_kfid", array.getJSONObject(0).getString("open_kfid"));
                        String kfUrlResult = wxCpServiceImpl.post(WxCpConstants.API_ADD_CONTACT_WAY, kfParamObj.toJSONString());
                        if (kfUrlResult != null) {
                            JSONObject kfUrlItem = JSON.parseObject(kfUrlResult);
                            map.put("url", kfUrlItem.getString("url"));
                            return new Result<>(map);
                        }
                    }
                }
            } else {
                String accessToken = getAccessToken(param.getId());
                String kfListResult = wxCpTpService.get(WxCpConstants.API_KF_LIST, "access_token=" + accessToken);
                if (StringUtils.isNotBlank(kfListResult)) {
                    JSONObject obj = JSON.parseObject(kfListResult);
                    if (obj != null) {
                        JSONArray array = obj.getJSONArray("account_list");
                        if (CollectionUtil.isNotEmpty(array)) {
                            JSONObject kfParamObj = new JSONObject();
                            kfParamObj.put("open_kfid", array.getJSONObject(0).getString("open_kfid"));
                            String kfUrlResult = wxCpTpService.post(WxCpConstants.API_ADD_CONTACT_WAY + "?access_token=" + accessToken, kfParamObj.toJSONString());
                            if (kfUrlResult != null) {
                                JSONObject kfUrlItem = JSON.parseObject(kfUrlResult);
                                map.put("url", kfUrlItem.getString("url"));
                                return new Result<>(map);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("getH5Kf fail: " + e.getMessage(), e);
        }
        return new Result<>(map);
    }

    private String getAccessToken(Long shopId) throws WxErrorException {
        String suiteTicket = (String)stringRedisService.get(WxCpConstants.SUITE_TICKET_KEY);
        wxCpTpService.setSuiteTicket(suiteTicket);

        CereCustomerServiceConfig config = cereCustomerServiceConfigService.getByShopId(shopId);
        if (config == null || StringUtils.isBlank(config.getAuthCorpId())
            || StringUtil.isBlank(config.getPermanentCode())) {
            return null;
        }
        WxAccessToken corpToken = wxCpTpService.getCorpToken(config.getAuthCorpId(), config.getPermanentCode());
        return corpToken.getAccessToken();
    }

    @GetMapping("getPCKf")
    @ApiOperation(value = "查询PC客服", notes = "id参数传店铺id, 不传则返回平台端的客服")
    public Result<Map<String, String>> getPCKf(CommonIdParam param) {
        Map<String, String> map = new HashMap<>();
        map.put("url", "");
        try {
            if (param == null || param.getId() == null || param.getId() == 0) {
                String kfListResult = wxCpServiceImpl.get(WxCpConstants.API_KF_LIST, null);
                JSONObject obj = JSON.parseObject(kfListResult);
                if (obj != null) {
                    JSONArray array = obj.getJSONArray("account_list");
                    if (array != null && array.size() > 0) {
                        Collections.shuffle(array);
                        JSONObject kfParamObj = new JSONObject();
                        kfParamObj.put("open_kfid", array.getJSONObject(0).getString("open_kfid"));
                        String kfUrlResult = wxCpServiceImpl.post(WxCpConstants.API_ADD_CONTACT_WAY, kfParamObj.toJSONString());
                        if (kfUrlResult != null) {
                            JSONObject kfUrlItem = JSON.parseObject(kfUrlResult);
                            map.put("url", kfUrlItem.getString("url"));
                            return new Result<>(map);
                        }
                    }
                }
            } else {
                String accessToken = getAccessToken(param.getId());
                String kfListResult = wxCpTpService.get(WxCpConstants.API_KF_LIST, "access_token=" + accessToken);
                if (StringUtils.isNotBlank(kfListResult)) {
                    JSONObject obj = JSON.parseObject(kfListResult);
                    if (obj != null) {
                        JSONArray array = obj.getJSONArray("account_list");
                        if (CollectionUtil.isNotEmpty(array)) {
                            JSONObject kfParamObj = new JSONObject();
                            kfParamObj.put("open_kfid", array.getJSONObject(0).getString("open_kfid"));
                            String kfUrlResult = wxCpTpService.post(WxCpConstants.API_ADD_CONTACT_WAY + "?access_token=" + accessToken, kfParamObj.toJSONString());
                            if (kfUrlResult != null) {
                                JSONObject kfUrlItem = JSON.parseObject(kfUrlResult);
                                map.put("url", kfUrlItem.getString("url"));
                                return new Result<>(map);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("getPCKf fail: " + e.getMessage(), e);
        }
        return new Result<>(map);
    }

    @GetMapping("getAppletKf")
    @ApiOperation(value = "查询小程序客服", notes = "id参数传店铺id, 不传则返回平台端的客服, 返回map key为corpId 和 url")
    public Result<Map<String, String>> getAppletKf(CommonIdParam param) {
        Map<String, String> map = new HashMap<>();
        map.put("url", "");
        log.info("getAppletKf {}", JSON.toJSONString(param));
        try {
            if (param == null || param.getId() == null || param.getId() == 0) {
                String result = wxCpServiceImpl.get(WxCpConstants.API_KF_LIST, null);
                JSONObject obj = JSON.parseObject(result);
                if (obj != null) {
                    JSONArray array = obj.getJSONArray("account_list");
                    if (array != null && array.size() > 0) {
                        Collections.shuffle(array);
                        JSONObject kfParamObj = new JSONObject();
                        kfParamObj.put("open_kfid", array.getJSONObject(0).getString("open_kfid"));
                        String kfUrlResult = wxCpServiceImpl.post(WxCpConstants.API_ADD_CONTACT_WAY, kfParamObj.toJSONString());
                        if (kfUrlResult != null) {
                            JSONObject kfUrlItem = JSON.parseObject(kfUrlResult);
                            map.put("corpId", wxCpServiceImpl.getWxCpConfigStorage().getCorpId());
                            map.put("url", kfUrlItem.getString("url"));
                            return new Result<>(map);
                        }
                    }
                }
            } else {
                String accessToken = getAccessToken(param.getId());
                String kfListResult = wxCpTpService.get(WxCpConstants.API_KF_LIST, "access_token=" + accessToken);
                if (StringUtils.isNotBlank(kfListResult)) {
                    JSONObject obj = JSON.parseObject(kfListResult);
                    if (obj != null) {
                        JSONArray array = obj.getJSONArray("account_list");
                        if (CollectionUtil.isNotEmpty(array)) {
                            JSONObject kfParamObj = new JSONObject();
                            kfParamObj.put("open_kfid", array.getJSONObject(0).getString("open_kfid"));
                            String kfUrlResult = wxCpTpService.post(WxCpConstants.API_ADD_CONTACT_WAY + "?access_token=" + accessToken, kfParamObj.toJSONString());
                            //String kfUrlResult = wxCpServiceImpl.post(WxCpConstants.API_ADD_CONTACT_WAY, kfParamObj.toJSONString());
                            if (kfUrlResult != null) {
                                JSONObject kfUrlItem = JSON.parseObject(kfUrlResult);
                                map.put("corpId", wxCpServiceImpl.getWxCpConfigStorage().getCorpId());
                                map.put("url", kfUrlItem.getString("url"));
                                return new Result<>(map);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("getAppletKf fail: " + e.getMessage(), e);
        }
        return new Result<>(map);
    }

    /**
     * 查询授权corpId
     * @return
     */
    private String getCorpId(Long shopId) {
        CereCustomerServiceConfig config = cereCustomerServiceConfigService.getByShopId(shopId);
        return config.getAuthCorpId();
    }
}
